package comgame.scenes;

import comgame.components.AttributeComponent;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.util.Objects;

import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.Entity;
import comgame.components.HealthComponent;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.animation.PauseTransition;
import javafx.util.Duration;
import comgame.entities.Player;
import comgame.entities.Enemy;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;

// 不继承FXGLScene
public class CombatScene {
    private Label playerHpLabel;
    private Label logLabel;
    private Entity playerEntity;
    private Entity MonsterEntity;
    private HealthComponent playerHp;
    private HealthComponent MonsterHp;
    private boolean playerTurn = true;
    private Player playerObj;
    private Enemy MonsterObj;
    private VBox vbox;
    
    // 关卡相关
    private int currentLevel;
    private LevelData.LevelInfo levelInfo;
    private Runnable onBattleComplete;
    
    // 添加背景图片引用，用于清理
    private ImageView battleBackground;
    
    // 第六关随机Boss选择
    private String selectedBoss;
    private String selectedBossKey;
    
    private boolean bossEntering = false;
    
    public CombatScene(int level, Runnable onBattleComplete) {
        this.currentLevel = level;
        this.levelInfo = LevelData.getInstance().getLevelInfo(level);
        this.onBattleComplete = onBattleComplete;
        
        // 第六关预先选择随机Boss
        if (level == 6) {
            Random random = new Random();
            if (random.nextBoolean()) {
                selectedBoss = "pumpking";
                selectedBossKey = "Pumpking";
            } else {
                selectedBoss = "everscream";
                selectedBossKey = "Everscream";
            }
        }
        
        // 清理可能存在的旧敌人实体
        cleanupExistingEnemies();
        
        // 背景：第8关用BossBackGround.png，其余用Combat_Background.jpg
        Image bgImg;
        if (currentLevel == 8) {
            bgImg = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/assets/textures/BossBackGround.png")));
        } else {
            bgImg = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/assets/textures/Combat_Background.jpg")));
        }
        battleBackground = new ImageView(bgImg);
        battleBackground.setFitWidth(FXGL.getAppWidth());
        battleBackground.setFitHeight(FXGL.getAppHeight());
        battleBackground.setPreserveRatio(false);
        FXGL.getGameScene().getContentRoot().getChildren().add(0, battleBackground);
        
        // 使用现有的玩家实体，而不是重新生成
        playerEntity = GameScene.playerEntity;
        if (playerEntity == null || !playerEntity.isActive()) {
            // 如果玩家实体不存在，则重新创建
            System.out.println("CombatScene: 重新创建玩家实体");
            GameScene.recreatePlayerEntity();
            playerEntity = GameScene.playerEntity;
        } else {
            // 如果玩家实体存在，将其移动到战斗位置
            playerEntity.setPosition(new javafx.geometry.Point2D(200, 400));
            if (playerEntity.hasComponent(com.almasb.fxgl.physics.PhysicsComponent.class)) {
                playerEntity.getComponent(com.almasb.fxgl.physics.PhysicsComponent.class)
                    .overwritePosition(new javafx.geometry.Point2D(200, 400));
            }
            playerEntity.getViewComponent().setVisible(true);
            System.out.println("战斗场景设置后玩家位置：" + playerEntity.getPosition());
        }
        // 根据关卡生成对应的敌人
        String enemyType = getEnemyTypeForLevel(currentLevel);
        double[] enemyPosition = getEnemyPositionForLevel(currentLevel);
        MonsterEntity = FXGL.spawn(enemyType, enemyPosition[0], enemyPosition[1]);
        
        // Boss关：入场动画
        if (currentLevel == 8 && MonsterEntity != null) {
            bossEntering = true;
            javafx.scene.Node bossNode = MonsterEntity.getViewComponent().getChildren().get(0);
            double startX = FXGL.getAppWidth() + 100;
            double targetX = enemyPosition[0];
            bossNode.setTranslateX(startX - targetX);
            javafx.animation.TranslateTransition moveIn = new javafx.animation.TranslateTransition(javafx.util.Duration.seconds(5.0), bossNode); // 更慢
            moveIn.setFromX(startX - targetX);
            moveIn.setToX(0);
            moveIn.setInterpolator(javafx.animation.Interpolator.EASE_BOTH);
            moveIn.setOnFinished(e -> {
                bossEntering = false;
                if(playerObj.getSpeed()<MonsterEntity.getComponent(AttributeComponent.class).getSpeed()) {
                    playerTurn = false;
                }
                nextTurn(); // 动画结束后自动开始战斗
            });
            moveIn.play();
        }
        
        // 安全检查：确保实体和组件都存在
        if (playerEntity != null && playerEntity.isActive()) {
            playerHp = comgame.scenes.GameScene.player.getHealthComponent();
            playerObj = GameScene.player; // 直接用GameScene.player
            // 确保玩家属性同步到组件
            playerObj.syncAttributesToComponent();
        }
        if (MonsterEntity != null && MonsterEntity.isActive()) {
            MonsterHp = MonsterEntity.getComponent(HealthComponent.class);
            String enemyKey = getEnemyKeyForLevel(currentLevel);
            MonsterObj = (Enemy) MonsterEntity.getObject(enemyKey);
        }
        setupEnemyStats();
        // UI
        playerHpLabel = new Label();
        logLabel = new Label();
        vbox = new VBox(10, playerHpLabel, logLabel);
        vbox.setLayoutX(50);
        vbox.setLayoutY(50);
        updateHpLabels();
        logLabel.setText("第" + level + "关战斗开始！");
        FXGL.getGameScene().addUINode(vbox);
        playerObj.restoreFullHealth();
        // 播放战斗音乐：第8关用BossFight.mp4，其余用NormalFight.mp4
        comgame.scenes.MusicManager.stopAll();
        // 每次都重新赋值battleMusic为对应关卡音乐
        if (currentLevel == 8) {
            comgame.scenes.MusicManager.battleMusic = FXGL.getAssetLoader().loadMusic("BossFight.mp4");
        } else {
            comgame.scenes.MusicManager.battleMusic = FXGL.getAssetLoader().loadMusic("NormalFight.mp4");
        }
        FXGL.getAudioPlayer().loopMusic(comgame.scenes.MusicManager.battleMusic);
        comgame.scenes.MusicManager.isBattleMusicPlaying = true;
        updateHpLabels();

        if(playerObj.getSpeed()<MonsterEntity.getComponent(AttributeComponent.class).getSpeed()) {
            playerTurn = false;
        }
        nextTurn();
    }
    
    private String getEnemyTypeForLevel(int level) {
        switch (level) {
            case 1:
                return "slime";
            case 2:
                return "bug";
            case 3:
                return "bulbapedia"; // 使用Bulbapedia作为第三关怪物
            case 4:
                return "ghost"; // 使用Ghost作为第四关怪物
            case 5:
                return "vegetabler"; // 使用Vegetabler作为第五关怪物
            case 6:
                return selectedBoss; // 使用预先选择的Boss
            case 7:
                return "empress_of_light"; // 使用Empress_of_Light作为第七关怪物
            case 8:
                return "plantera"; // Boss实体类型
            default:
                return "slime";
        }
    }
    
    private String getEnemyKeyForLevel(int level) {
        switch (level) {
            case 1:
                return "Slime";
            case 2:
                return "Bug";
            case 3:
                return "Bulbapedia"; // 使用Bulbapedia作为第三关怪物
            case 4:
                return "Ghost"; // 使用Ghost作为第四关怪物
            case 5:
                return "Vegetabler"; // 使用Vegetabler作为第五关怪物
            case 6:
                return selectedBossKey; // 使用预先选择的Boss键
            case 7:
                return "Empress_of_Light"; // 使用Empress_of_Light作为第七关怪物
            case 8:
                return "Plantera"; // Boss实体key
            default:
                return "Slime";
        }
    }
    
    private double[] getEnemyPositionForLevel(int level) {
        switch (level) {
            case 1:
                return new double[]{600, 400};
            case 2:
                return new double[]{600, 400};
            case 3:
                return new double[]{600, 400};
            case 4:
                return new double[]{600,400};
            case 5:
                return new double[]{600, 400};
            case 6:
                return new double[]{500, 300};
            case 7:
                return new double[]{500, 300};
            default:
                return new double[]{600, 300};
        }
    }
    
    // 清理可能存在的旧敌人实体
    private void cleanupExistingEnemies() {
        // 获取所有敌人实体并移除它们
        List<Entity> enemiesToRemove = FXGL.getGameWorld().getEntitiesByType(comgame.entities.EntityType.ENEMY);
        
        // 移除所有找到的敌人实体
        for (Entity enemy : enemiesToRemove) {
            if (enemy != null && enemy.isActive()) {
                System.out.println("清理旧敌人实体: " + enemy.getType());
                enemy.removeFromWorld();
            }
        }
        
        if (!enemiesToRemove.isEmpty()) {
            System.out.println("清理了 " + enemiesToRemove.size() + " 个旧敌人实体");
        }
    }
    
    private void setupEnemyStats() {
        if (levelInfo != null && MonsterHp != null) {
            // 设置敌人血量
            MonsterHp.setMaxHealth(levelInfo.getMonsterHealth());
            MonsterHp.setHealth(levelInfo.getMonsterHealth());
            
            // 设置敌人攻击力（通过属性组件）
            var enemyAttribute = MonsterEntity.getComponent(comgame.components.AttributeComponent.class);
            if (enemyAttribute != null) {
                enemyAttribute.setAttack(levelInfo.getMonsterAttack());
                enemyAttribute.setDefense(levelInfo.getMonsterDefense());
                enemyAttribute.setCritRate(levelInfo.getMonsterCritRate());
                enemyAttribute.setSpeed(levelInfo.getMonsterSpeed());
            }
        }
    }

    private void updateHpLabels() {
        if (playerHp != null) {
            playerHpLabel.setText("玩家HP: " + playerHp.getHealth() + "/" + playerHp.getMaxHealth());
        }
        if (MonsterHp != null && levelInfo != null) {
            // 敌人血条不再显示在UI上
        }
    }

    private void nextTurn() {
        if (currentLevel == 8 && bossEntering) {
            return;
        }
        // 安全检查
        if (playerHp == null || MonsterHp == null || playerObj == null || MonsterObj == null) {
            System.err.println("战斗组件缺失，结束战斗");
            showBattleResult(false);
            return;
        }
        
        if (playerHp.getHealth() <= 0) {
            logLabel.setText("你输了！");
            // 战斗失败
            showBattleResult(false);
            return;
        }
        if (MonsterHp.getHealth() <= 0) {
            logLabel.setText("你赢了！");
            // 战斗胜利
            showBattleResult(true);
            return;
        }
        if (playerTurn) {
            playerObj.attack(MonsterObj); // 玩家攻击敌人
            updateHpLabels();
            if (levelInfo != null) {
                logLabel.setText("玩家攻击" + levelInfo.getMonsterName() + "！");
            }
        } else {
            MonsterObj.attack(playerObj); // 敌人攻击玩家
            updateHpLabels();
            if (levelInfo != null) {
                logLabel.setText(levelInfo.getMonsterName() + "攻击玩家！");
            }
        }
        playerTurn = !playerTurn;
        // 增加回合间隔，确保攻击动画完全结束
        // 攻击动画总时长约为1.7秒，加上一些缓冲时间
        PauseTransition pause = new PauseTransition(Duration.seconds(2.1));
        pause.setOnFinished(e -> nextTurn());
        pause.play();
    }
    
    private void showBattleResult(boolean isVictory) {
        // 停止战斗音乐并重置isBattleMusicPlaying
        comgame.scenes.MusicManager.stopBattleMusic();
        comgame.scenes.MusicManager.isBattleMusicPlaying = false;
        if (!comgame.scenes.MusicManager.isHomeMusicPlaying) {
            if (comgame.scenes.MusicManager.homeMusic == null)
                comgame.scenes.MusicManager.homeMusic = FXGL.getAssetLoader().loadMusic("HomeMusic.mp4");
            FXGL.getAudioPlayer().loopMusic(comgame.scenes.MusicManager.homeMusic);
            comgame.scenes.MusicManager.isHomeMusicPlaying = true;
        }
        
        // 清理战斗场景
        FXGL.getGameScene().clearUINodes();
        
        // 移除战斗背景图片
        if (battleBackground != null) {
            FXGL.getGameScene().getContentRoot().getChildren().remove(battleBackground);
        }
        
        // 移除敌人实体
        if (MonsterEntity != null && MonsterEntity.isActive()) {
            MonsterEntity.removeFromWorld();
        }
        
        // 隐藏玩家实体（在战斗结果UI显示期间）
        if (playerEntity != null && playerEntity.isActive()) {
            playerEntity.getViewComponent().setVisible(false);
        }
        
        List<String> rewards = new ArrayList<>();
        if (isVictory) {
            // 恢复玩家血量到满血
            if (playerObj != null) {
                playerObj.restoreFullHealth();
                System.out.println("玩家胜利，血量已恢复");
            }
            // 新boss击败标志和推进轮次只在胜利时设置
            if (currentLevel == 8) {
                comgame.scenes.AltarScene.newBossDefeated = true;
                comgame.scenes.AltarScene.currentRound = 3;
                comgame.scenes.AltarScene.cropClickedCount = 0;
                for (int i = 0; i < comgame.scenes.AltarScene.cropSacrificed.length; i++) {
                    if (comgame.scenes.AltarScene.getCropRound(i) == 3) {
                        comgame.scenes.AltarScene.cropSacrificed[i] = false;
                        comgame.scenes.AltarScene.cropClicked[i] = false;
                    }
                }
            }

            // 经验奖励：敌人最大血量
            int exp = 0;
            if (MonsterHp != null) {
                exp = MonsterHp.getMaxHealth();
            } else if (levelInfo != null) {
                exp = levelInfo.getMonsterHealth();
            } else {
                exp = 50; // 默认经验
            }
            if (playerObj != null) {
                System.out.println("战斗胜利，获得经验: " + exp + ", 当前等级: " + playerObj.getCombatLevel() + ", 当前经验: " + playerObj.getCombatExp());
                playerObj.addCombatExpAndLevelUp(exp);
                System.out.println("经验添加后，等级: " + playerObj.getCombatLevel() + ", 经验: " + playerObj.getCombatExp());
                rewards.add("获得经验：" + exp);
                
                // 自动存档，确保经验数据被保存
                comgame.scenes.DataSaveManager.saveAll();
                System.out.println("战斗胜利后自动存档完成");
                
                // 强制刷新属性面板
                comgame.scenes.GameScene.forceUpdatePlayerInfoPanel();
                System.out.println("已触发属性面板强制刷新");
            }

            // 生成实际掉落物
            Random random = new Random();
            switch (currentLevel) {
                case 1: // 史莱姆
                    int slimeCount = 2 + random.nextInt(2); // 2-3个
                    ItemManager.getInstance().addItem("史莱姆凝胶", slimeCount);
                    rewards.add("史莱姆凝胶 x" + slimeCount);
                    if (random.nextDouble() < 0.10) {
                        String[] seeds = {"胡萝卜种子", "土豆种子", "小麦种子", "番茄种子"};
                        for (int i = 0; i < 2; i++) {
                            String seed = seeds[random.nextInt(seeds.length)];
                            ItemManager.getInstance().addItem(seed, 1);
                            rewards.add("获得：" + seed);
                        }
                    }
                    break;
                case 2: // 虫子
                    int bugMeatCount = 1 + random.nextInt(2); // 1-2个
                    ItemManager.getInstance().addItem("昆虫肉", bugMeatCount);
                    rewards.add("昆虫肉 x" + bugMeatCount);
                    if (random.nextDouble() < 0.20) {
                        ItemManager.getInstance().addItem("霜瓜种子", 1 + random.nextInt(2));
                        rewards.add("霜瓜种子 x" + (1 + random.nextInt(2)));
                    }
                    break;
                case 3: // 妙蛙种子
                    // 50%失败，30%普通，15%优秀，4%史诗，1%传说
                    double roll = random.nextDouble();
                    if (roll < 0.5) {
                        // 奴役失败
                        FXGL.showConfirm("是否尝试奴役第三关怪物？", yes -> {
                            if (yes) {
                                FXGL.showMessage("奴役失败，未获得自动化种田能力！");
                                FXGL.set("auto_farm_enabled", false);
                            } else {
                                FXGL.set("auto_farm_enabled", false);
                            }
                        });
                        rewards.add("妙蛙种子 (可服役)");
                    } else if (roll < 0.8) {
                        FXGL.showConfirm("是否尝试奴役第三关怪物？", yes -> {
                            if (yes) {
                                FXGL.showMessage("奴役成功！等级：普通，已开启自动化种田。");
                                FXGL.set("auto_farm_enabled", true);
                                FXGL.set("auto_farm_unlocked", true);
                                FXGL.set("auto_farm_level", "普通");
                                FXGL.set("auto_farm_interval", 2.0);
                            } else {
                                FXGL.set("auto_farm_enabled", false);
                            }
                        });
                        rewards.add("妙蛙种子 (可服役)");
                    } else if (roll < 0.95) {
                        FXGL.showConfirm("是否尝试奴役第三关怪物？", yes -> {
                            if (yes) {
                                FXGL.showMessage("奴役成功！等级：优秀，已开启自动化种田。");
                                FXGL.set("auto_farm_enabled", true);
                                FXGL.set("auto_farm_unlocked", true);
                                FXGL.set("auto_farm_level", "优秀");
                                FXGL.set("auto_farm_interval", 1.0);
                            } else {
                                FXGL.set("auto_farm_enabled", false);
                            }
                        });
                        rewards.add("妙蛙种子 (可服役)");
                    } else if (roll < 0.99) {
                        FXGL.showConfirm("是否尝试奴役第三关怪物？", yes -> {
                            if (yes) {
                                FXGL.showMessage("奴役成功！等级：史诗，已开启自动化种田。");
                                FXGL.set("auto_farm_enabled", true);
                                FXGL.set("auto_farm_unlocked", true);
                                FXGL.set("auto_farm_level", "史诗");
                                FXGL.set("auto_farm_interval", 0.5);
                            } else {
                                FXGL.set("auto_farm_enabled", false);
                            }
                        });
                        rewards.add("妙蛙种子 (可服役)");
                    } else {
                        FXGL.showConfirm("是否尝试奴役第三关怪物？", yes -> {
                            if (yes) {
                                FXGL.showMessage("奴役成功！等级：传说，已开启自动化种田。");
                                FXGL.set("auto_farm_enabled", true);
                                FXGL.set("auto_farm_unlocked", true);
                                FXGL.set("auto_farm_level", "传说");
                                FXGL.set("auto_farm_interval", 0.1);
                            } else {
                                FXGL.set("auto_farm_enabled", false);
                            }
                        });
                        rewards.add("妙蛙种子 (可服役)");
                    }
                    break;
                case 4: // 幽灵
                    double drop = random.nextDouble();
                    if (drop < 0.3) {
                        rewards.add("什么都没有");
                    } else if (drop < 0.45) {
                        // 幽灵剑
                        ItemManager.getInstance().addItem("幽灵剑", 1);
                        rewards.add("幽灵剑");
                    } else if (drop < 0.95) {
                        // 幽灵一套
                        String[] ghostSet = {"幽灵靴子", "幽灵护腿", "幽灵胸甲", "幽灵头盔"};
                        String equip = ghostSet[random.nextInt(ghostSet.length)];
                        ItemManager.getInstance().addItem(equip, 1);
                        rewards.add(equip);
                    } else {
                        // 稀有幽灵一套
                        String[] ghostSet = {"幽灵靴子", "幽灵护腿", "幽灵胸甲", "幽灵头盔"};
                        for (String equip : ghostSet) {
                            ItemManager.getInstance().addItem(equip, 1);
                        }
                        rewards.add("幽灵一套(稀有)");
                    }
                    // 大幅提高种子掉落率和数量
                    if (random.nextDouble() < 0.85) { // 从50%提高到85%
                        int count = 1 + random.nextInt(7); // 从3-4个提高到8-14个
                        ItemManager.getInstance().addItem("霜瓜种子", count);
                        rewards.add("霜瓜种子 x" + count);
                    }
                    // 额外掉落其他种子
                    if (random.nextDouble() < 0.60) { // 60%概率掉落其他种子
                        String[] extraSeeds = {"星果种子", "南瓜种子", "幽灵辣椒种子", "水龙果种子"};
                        String extraSeed = extraSeeds[random.nextInt(extraSeeds.length)];
                        int extraCount = 3 + random.nextInt(4); // 3-6个
                        ItemManager.getInstance().addItem(extraSeed, extraCount);
                        rewards.add(extraSeed + " x" + extraCount);
                    }
                    break;
                case 5: // 蔬菜人
                    double r = random.nextDouble();
                    if (r < 0.4) { // 一级种子
                        int count = 3 + random.nextInt(7); // 15-24个
                        // 随机一级种子
                        String[] seeds = {"胡萝卜种子", "土豆种子", "小麦种子", "番茄种子"};
                        for (int i = 0; i < count; i++) {
                            String seed = seeds[random.nextInt(seeds.length)];
                            ItemManager.getInstance().addItem(seed, 1);
                            rewards.add("获得：" + seed);
                        }
                    } else if (r < 0.7) { // 二级种子
                        int count = 3 + random.nextInt(4); // 8-14个
                        // 随机二级种子
                        String[] seeds = {"星果种子", "南瓜种子", "霜瓜种子", "幽灵辣椒种子", "水龙果种子", "齐瓜种子"};
                        for (int i = 0; i < count; i++) {
                            String seed = seeds[random.nextInt(seeds.length)];
                            ItemManager.getInstance().addItem(seed, 1);
                            rewards.add("获得：" + seed);
                        }
                    } else {
                        // 齐瓜掉落
                        int qiCount = 5 + random.nextInt(6); // 5-10个
                        ItemManager.getInstance().addItem("齐瓜", qiCount);
                        rewards.add("齐瓜 x" + qiCount);
                    }
                    // 额外掉落（与主要掉落类型相同）
                    if (random.nextDouble() < 0.80) { // 80%概率额外掉落
                        if (r < 0.4) {
                            // 如果主要掉落是一级种子，额外掉落也是一级种子
                            String[] bonusSeeds = {"胡萝卜种子", "土豆种子", "小麦种子", "番茄种子"};
                            String bonusSeed = bonusSeeds[random.nextInt(bonusSeeds.length)];
                            int bonusCount = 4 + random.nextInt(5); // 4-8个
                            ItemManager.getInstance().addItem(bonusSeed, bonusCount);
                            rewards.add("额外获得：" + bonusSeed + " x" + bonusCount);
                        } else if (r < 0.7) {
                            // 如果主要掉落是二级种子，额外掉落也是二级种子
                            String[] bonusSeeds = {"星果种子", "南瓜种子", "霜瓜种子", "幽灵辣椒种子", "水龙果种子", "齐瓜种子"};
                            String bonusSeed = bonusSeeds[random.nextInt(bonusSeeds.length)];
                            int bonusCount = 4 + random.nextInt(5); // 4-8个
                            ItemManager.getInstance().addItem(bonusSeed, bonusCount);
                            rewards.add("额外获得：" + bonusSeed + " x" + bonusCount);
                        } else {
                            // 如果主要掉落是齐瓜，额外掉落也是齐瓜
                            int bonusCount = 2 + random.nextInt(3); // 2-4个
                            ItemManager.getInstance().addItem("齐瓜", bonusCount);
                            rewards.add("额外获得：齐瓜 x" + bonusCount);
                        }
                    }
                    break;
                case 6: // 南瓜王/常绿尖叫怪
                    if (selectedBoss != null && selectedBoss.equals("pumpking")) {
                        if (random.nextDouble() < 0.37) {
                            ItemManager.getInstance().addItem("无头骑士剑", 1);
                            rewards.add("无头骑士剑");
                        }
                        ItemManager.getInstance().addItem("南瓜种子", 100);
                        rewards.add("南瓜种子 x100");
                    } else {
                        if (random.nextDouble() < 0.37) {
                            ItemManager.getInstance().addItem("喜庆之翼", 1);
                            rewards.add("喜庆之翼");
                        }
                    }
                    break;
                case 7: // Boss
                    if (random.nextDouble() < 0.3) {
                        String[] spaceSet = {"空间之主靴子", "空间之主护腿", "空间之主胸甲", "空间之主头盔"};
                        String equip = spaceSet[random.nextInt(spaceSet.length)];
                        ItemManager.getInstance().addItem(equip, 1);
                        rewards.add(equip);
                    }
                    if (random.nextDouble() < 0.3) {
                        ItemManager.getInstance().addItem("泰拉棱镜", 1);
                        rewards.add("泰拉棱镜");
                    }
                    break;
                case 8: // 世纪之花
                    ItemManager.getInstance().addItem("世纪之花", 1);
                    rewards.add("世纪之花");
                    break;
            }
            // 解锁下一关
            LevelData.getInstance().unlockLevel(currentLevel + 1);
        }
        
        // 显示战斗结果UI
        BattleResultUI resultUI = new BattleResultUI(
            isVictory, 
            rewards,
            () -> {
                // 下一关 - 使用延迟执行避免递归问题
                if (isVictory && LevelData.getInstance().isLevelUnlocked(currentLevel + 1)) {
                    FXGL.runOnce(() -> {
                        FXGL.getGameScene().clearUINodes();
                        new CombatScene(currentLevel + 1, onBattleComplete);
                    }, Duration.seconds(0.1));
                }
            },
            () -> {
                // 返回地图 - 使用延迟执行避免递归问题
                FXGL.runOnce(() -> {
                    // 如果玩家实体不存在或不活跃，重新创建
                    if (comgame.scenes.GameScene.playerEntity == null || !comgame.scenes.GameScene.playerEntity.isActive()) {
                        comgame.scenes.GameScene.recreatePlayerEntity();
                    } else {
                        // 如果玩家实体存在，确保可见
                        comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(true);
                    }
                    if (onBattleComplete != null) {
                        onBattleComplete.run();
                    }
                }, Duration.seconds(0.1));
            },
            () -> {
                // 再次挑战当前关卡 - 使用延迟执行避免递归问题
                FXGL.runOnce(() -> {
                    FXGL.getGameScene().clearUINodes();
                    new CombatScene(currentLevel, onBattleComplete);
                }, Duration.seconds(0.1));
            },
            currentLevel // 传递关卡参数
        );
        
        FXGL.getGameScene().addUINode(resultUI);
    }

}